package com.xnew.userOrg.controller;


import com.alibaba.fastjson.JSONObject;
import com.xnew.aes.LogParameter;
import com.xnew.bean.common.SysOrgUserInfo;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.bean.common.T10MemOrgLinkmanInfo;
import com.xnew.constant.Constant;
import com.xnew.entity.ssoApi.*;
import com.xnew.exception.CustomException;
import com.xnew.ssoApi.mapper.SysUserInfoMapper;
import com.xnew.ssoApi.service.SsoApiService;
import com.xnew.userOrg.service.SysOrgInfoService;
import com.xnew.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


@CrossOrigin
@RestController
@RequestMapping("/sysOrgUser")
public class SysOrgInfoController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private SysOrgInfoService sysOrgInfoService;
	@Resource
	private SsoApiService ssoApiService;
	@Resource
	private SysUserInfoMapper t61SysUserInfoMapper;

	@Value("${SSO.subSystem1}")
	private String subSystem1 ; //	会员系统编号
	@Value("${SSO.subSystem2}")
	private String subSystem2 ; //	报送系统编号
	@Value("${SSO.Client_id}")
	private String Client_id ; //	系统编号
	
	/**
	 * 删除机构用户
	 */
	@RequestMapping("/delSysOrgUser")
	@LogParameter(key = "", desc = "删除机构用户")
	public DataOutput delSysOrgUser (@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		if (input.getParam() == null ||
			input.getParam().get("orgId") == null ||
			StringUtils.isEmpty(input.getParam().get("orgId").toString()) ||
			input.getParam().get("userInfoNo") == null ||
			StringUtils.isEmpty(input.getParam().get("userInfoNo").toString())
		){
			out.setCode(-90001);
			out.setMsg("缺少必填字段！");
			return out;
		}
		try {
			sysOrgInfoService.delSysOrgUser(input.getParam().get("userInfoNo").toString(),input.getParam().get("orgId").toString());

			SysUserInfo oginUser = UserUtil.getUserInfo(request);
			String code = oginUser!=null && oginUser.getCode()!=null?oginUser.getCode().trim():null;
			String access_token = oginUser!=null && oginUser.getAccess_token()!=null?oginUser.getAccess_token().trim():null;
			if(code!=null && !code.equals("")){
				if(Client_id!=null && !Client_id.equals("")){
					System.out.println("====推送门户开始====");
					Map param = input.getParam();
					System.out.println("param:" + param);
					String[] subSystems = new String[]{subSystem1,subSystem2};
					OrgAccountStateVo reg = new OrgAccountStateVo();
					if(null!=param.get("access_token") && !((String)param.get("access_token")).equals("")) reg.setAccess_token((String)param.get("access_token"));//是 token
					if(null!=param.get("openId") && !((String)param.get("openId")).equals("")) reg.setOpenId((String)param.get("openId"));//用户 openId
					reg.setAccess_token("1234567890");
					reg.setSubSystems(subSystems);
					reg.setState(3);
					ResultDo obj = ssoApiService.OrgAccountState(reg);
					out.setMsg(obj.getMsg());
					out.setCode(obj.getCode());
					out.setData(ConvertEntityUtil.convertEntityData(obj));
					System.out.println("====推送门户结束====");
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			out.setCode(-90001);
			out.setMsg("操作失败！");
		}
		return out;
	}

    /**
     * 状态变更机构用户
     */
    @RequestMapping("/statusSysOrgUser")
    @LogParameter(key = "", desc = "状态变更机构用户")
    public DataOutput statusSysOrgUser (@RequestBody DataInput input, HttpServletRequest request) {
        DataOutput out = DataOutput.success();
        if (input.getParam() == null ||
                input.getParam().get("orgId") == null ||
                StringUtils.isEmpty(input.getParam().get("orgId").toString()) ||
                input.getParam().get("status") == null ||
                StringUtils.isEmpty(input.getParam().get("status").toString())
        ){
            out.setCode(-90001);
            out.setMsg("缺少必填字段！");
            return out;
        }
        try {
            sysOrgInfoService.updateSysOrgUserStatus(input.getParam().get("orgId").toString(),input.getParam().get("status").toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            out.setCode(-90001);
            out.setMsg("操作失败！");
        }
        return out;
    }
	/**
	 * 机构用户列表
	 */
	@RequestMapping("/queryOrgUserList")
	@LogParameter(key = "", desc = "机构用户列表")
	public DataOutput queryOrgUserList (@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		try{
			List<SysOrgUserInfo> list = sysOrgInfoService.queryOrgUserList(input);
			out= MybatisParam.getOutput(ConvertEntityUtil.convertListData(list));
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			out.setCode(-90001);
			out.setMsg("机构用户查询列表出错！");
		}
		return out;
	}


	/**
	 * 待选角色机构用户列表
	 */
	@RequestMapping("/queryOrgUserAddRoleList")
	@LogParameter(key = "", desc = "机构用户列表")
	public DataOutput queryOrgUserAddRoleList (@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		try{
			List<SysUserInfo> list = sysOrgInfoService.queryOrgUserAddRoleList(input);
			out= MybatisParam.getOutput(ConvertEntityUtil.convertListData(list));
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			out.setCode(-90001);
			out.setMsg("机构用户查询列表出错！");
		}
		return out;
	}


	/**
	 * 新增机构用户
	 */
	@RequestMapping("/insertOrgUser")
	@LogParameter(key = "", desc = "新增机构用户")
	public DataOutput insertOrgUser(@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		if(
			input.getParam().get("orgAttrCode") == null || input.getParam().get("loginName") == null
			|| StringUtils.isEmpty(input.getParam().get("orgAttrCode").toString())
			|| StringUtils.isEmpty(input.getParam().get("loginName").toString())
			|| input.getParam().get("orgName") == null || StringUtils.isEmpty(input.getParam().get("orgName").toString())
			|| input.getParam().get("orgCode") == null || StringUtils.isEmpty(input.getParam().get("orgCode").toString())
			|| input.getParam().get("orgCertifNo") == null || StringUtils.isEmpty(input.getParam().get("orgCertifNo").toString())
			|| input.getParam().get("aoiOrgNo") == null || StringUtils.isEmpty(input.getParam().get("aoiOrgNo").toString())
			|| input.getParam().get("beltoRegiCode") == null || StringUtils.isEmpty(input.getParam().get("beltoRegiCode").toString())
			|| input.getParam().get("orgAttrCode") == null || StringUtils.isEmpty(input.getParam().get("orgAttrCode").toString())
			|| input.getParam().get("orgTypeCode") == null || StringUtils.isEmpty(input.getParam().get("orgTypeCode").toString())
		){
			out.setCode(-30000);
			out.setMsg("缺少必选参数");
			return out;
		}
		try{
			Map<String,String> linkmanInfoTempMap = (Map<String, String>) input.getParam().get("memOrgLinkmanInfo");
			SysUserInfo userInfo = UserUtil.getUserInfo(request);
			SysOrgUserInfo orgUser = new SysOrgUserInfo();
			orgUser = (SysOrgUserInfo)ConvertEntityUtil.convertEntityByParam(input.getParam(), orgUser);
			T10MemOrgLinkmanInfo memOrgLinkmanInfo = new T10MemOrgLinkmanInfo();
			memOrgLinkmanInfo = (T10MemOrgLinkmanInfo) ConvertEntityUtil.convertEntityByParam(linkmanInfoTempMap, memOrgLinkmanInfo);
			orgUser.setMemOrgLinkmanInfo(memOrgLinkmanInfo);
			out = sysOrgInfoService.insertOrgUser(orgUser,userInfo,request);
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			out.setCode(-90001);
			out.setMsg("新增机构用户出错！"+ e.getMessage());
		}
		return out;
	}

	/**
	 * 修改机构用户
	 */
	@RequestMapping("/updateOrgUser")
	@LogParameter(key = "", desc = "修改机构用户")
	public DataOutput updateOrgUser (@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		if(
			input.getParam().get("orgId") == null || StringUtils.isEmpty(input.getParam().get("orgId").toString())
			|| input.getParam().get("orgAttrCode") == null || input.getParam().get("loginName") == null
			|| StringUtils.isEmpty(input.getParam().get("orgAttrCode").toString())
			|| StringUtils.isEmpty(input.getParam().get("loginName").toString())
			|| input.getParam().get("orgName") == null || StringUtils.isEmpty(input.getParam().get("orgName").toString())
			|| input.getParam().get("orgCode") == null || StringUtils.isEmpty(input.getParam().get("orgCode").toString())
			|| input.getParam().get("orgCertifNo") == null || StringUtils.isEmpty(input.getParam().get("orgCertifNo").toString())
			|| input.getParam().get("aoiOrgNo") == null || StringUtils.isEmpty(input.getParam().get("aoiOrgNo").toString())
			|| input.getParam().get("beltoRegiCode") == null || StringUtils.isEmpty(input.getParam().get("beltoRegiCode").toString())
			|| input.getParam().get("orgAttrCode") == null || StringUtils.isEmpty(input.getParam().get("orgAttrCode").toString())
			|| input.getParam().get("orgTypeCode") == null || StringUtils.isEmpty(input.getParam().get("orgTypeCode").toString())
		){
			out.setCode(-30000);
			out.setMsg("缺少必选参数");
			return out;
		}
		try{
			SysUserInfo userInfo = UserUtil.getUserInfo(request);
			SysOrgUserInfo orgUser = new SysOrgUserInfo();
			orgUser = (SysOrgUserInfo)ConvertEntityUtil.convertEntityByParam(input.getParam(),orgUser);
			Map<String,String> linkmanInfoTempMap = (Map<String, String>) input.getParam().get("memOrgLinkmanInfo");
			T10MemOrgLinkmanInfo memOrgLinkmanInfo = new T10MemOrgLinkmanInfo();
			memOrgLinkmanInfo =(T10MemOrgLinkmanInfo) ConvertEntityUtil.convertEntityByParam(linkmanInfoTempMap, memOrgLinkmanInfo);
			orgUser.setMemOrgLinkmanInfo(memOrgLinkmanInfo);
			sysOrgInfoService.updateOrgUser(orgUser,userInfo,request);
			out.setMsg("修改机构用户成功！");
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			out.setCode(-90001);
			out.setMsg("操作失败！" + e.getMessage());
		}
		return out;
	}


	/**
	 * 查询机构用户
	 */
	@RequestMapping("/queryOrgUser")
	@LogParameter(key = "", desc = "查询机构用户")
	public DataOutput queryOrgUser (@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		if(input.getParam().get("orgId") == null || StringUtils.isEmpty(input.getParam().get("orgId").toString())){
			out.setCode(-30000);
			out.setMsg("缺少必选参数");
			return out;
		}
		try{
			SysOrgUserInfo info = sysOrgInfoService.queryOrgUser(input.getParam().get("orgId").toString());
			out.setData(ConvertEntityUtil.convertEntityData(info));
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			out.setCode(-90001);
			out.setMsg("机构用户查询出错！");
		}
		return out;
	}

	/**
	 * 根据角色Id查询机构用户
	 */
	@RequestMapping("/queryOrgUserRoleList")
	@LogParameter(key = "", desc = "根据角色Id查询机构用户")
	public DataOutput queryOrgUserRoleList (@RequestBody DataInput input, HttpServletRequest request) {
		DataOutput out = DataOutput.success();
		if(input.getParam().get("arId") == null ||StringUtils.isEmpty(input.getParam().get("arId").toString())){
			out.setCode(-3000);
			out.setMsg("缺少必填参数，请检查后重试！");
			return  out;
		}
		try {
			List<SysUserInfo> orgUserList = sysOrgInfoService.queryOrgUserRoleList(input);
			out = MybatisParam.getOutput(ConvertEntityUtil.convertListData(orgUserList));
		} catch (Exception e) {
			e.printStackTrace();
			out.setCode(-91001);
			out.setMsg("查询列表失败!");
		}
		return out;
	}

}
